package controllers.systemadmin

import javax.inject.Inject

import controllers.BaseController
import models.JsonFormatters.{organizationFormatter, organizationQueryFormatter}
import models.{Organization, OrganizationQuery}
import repos.OrganizationRepository

import scala.concurrent.ExecutionContext.Implicits.global


class OrganizationController @Inject()(organizationRepository: OrganizationRepository) extends BaseController {

  import organizationRepository.dbConfig.driver.api._

  def list = jsonAction[OrganizationQuery] {
    (param, request) => {
      organizationRepository.filter(o => {
        param.id.map(o.id === _).getOrElse(LiteralColumn(true)) &&
          param.orgName.map(o.orgName.like(_)).getOrElse(LiteralColumn(true)) &&
          param.parentId.map(o.parentId === _).getOrElse(LiteralColumn(Option(true))) &&
          param.orgPath.map(o.orgPath like (_)).getOrElse(LiteralColumn(true))
      }, param.page.get, param.pageSize)
        .map(r => {
          Map("success" -> true,
            "message" -> "list complete",
            "total" -> r._1,
            "data" -> r._2)
        })
    }
  }

  def add = authJsonAction[Organization](Array("admin")) {
    (param, request) => {
      organizationRepository.save(param).map(r => {
        Map("success" -> true,
          "message" -> "add complete",
          "resultCode" -> 0,
          "data" -> r.id)
      })
    }
  }


  def modify = authJsonAction[Organization](Array("admin")) {
    (param, request) => {
      organizationRepository.update(param).map(r => {
        Map("success" -> true,
          "message" -> "modify complete",
          "resultCode" -> 0)
      })
    }
  }

  def remove = authJsonAction[Int](Array("admin")) {
    (param, request) => {
      organizationRepository.remove(param).map(r => {
        Map("success" -> true,
          "message" -> "remove complete",
          "resultCode" -> 0)
      })
    }
  }

  def find = jsonAction[Int] {
    (param, request) => {
      organizationRepository.getById(param).map(r => {
        Map("success" -> true,
          "message" -> "find complete",
          "resultCode" -> 0,
          "data" -> r)
      })
    }
  }
}
